package com.mrd.gtimp.business.service;

import com.mrd.base.BaseBiz;
import com.mrd.exception.QueryException;
import com.mrd.exception.SaveException;
import com.mrd.framework.ui.Jqgrid;
import com.mrd.gtimp.business.entity.CompanyQp;
import com.mrd.gtimp.business.entity.CompanyQpTemp;
import com.mrd.gtimp.business.entity.ConsigneeConsignorDP;
import com.mrd.gtimp.business.repository.CompanyQpDao;
import com.mrd.gtimp.business.repository.CompanyQpTempDao;
import com.mrd.gtimp.business.repository.ConsigneeConsignorDPDao;
import com.mrd.spring.repository.BaseRepository;
import com.mrd.util.LoginUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.transaction.Transactional;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Created by dengdc on 2016/10/29.
 */
@Service
public class CompanyQpTempBiz extends BaseBiz<CompanyQpTemp> {
    private static final Logger LOGGER = Logger.getLogger(CompanyQpTempBiz.class);
    @Resource
    private CompanyQpDao companyQpDao;

    @Resource
    @Qualifier("companyQpTempDao")
    public void setBaseRepository(BaseRepository<CompanyQpTemp, String> baseRepository) {
        super.baseRepository = baseRepository;
    }

    @Resource
    private CompanyQpTempDao companyQpTempDao;
    @Resource
    private ConsigneeConsignorDPDao consigneeConsignorDPDao;


    /**
     * 保存用户提交的供应商信息
     *
     * @param temp 供应商信息
     */
    @Transactional
    public void saveCompanyQpTemp(CompanyQpTemp temp){
        temp.setSubmitTime(new Date());
        temp.setSubmitor(LoginUtil.getLoginUser());
        temp.setFrom(CompanyQpTemp.FROM_FIRST_SUBMIT);
        temp.setSeriesNum(CompanyQpTemp.generateSeriesNum());
        temp.setReferenceCompanyId(LoginUtil.getLoginUser().getCompany().getId());
        temp.setClosed(CompanyQpTemp.CLOSED_0);
        trim(temp);
        //CompanyQpTemp tempT=getCompanyQpTempNotTrim(temp);
        baseRepository.save(temp);
        LOGGER.info("保存收发货人信息:" + temp.toString());
    }

    /***
     * 去除字符串的空格
     * @param temp
     * @throws NoSuchMethodException
     * @throws InvocationTargetException
     * @throws IllegalAccessException
     */
    private void trim(CompanyQpTemp temp)  {

        Field[] f = temp.getClass().getDeclaredFields();
        for (int i=0;i<f.length;i++){
            String type = f[i].getGenericType().toString();
            String name=f[i].getName();
            f[i].setAccessible(true);
            name = name.replaceFirst(name.substring(0, 1), name.substring(0, 1)
                    .toUpperCase());
            if (type.equals("class java.lang.String")){
                try {
                    Method m = temp.getClass().getMethod("get" + name);
                    String value= (String) m.invoke(temp);
                    Method s = temp.getClass().getMethod("set" + name,String.class);
                    if (value!=null&&!"".equals(value)){
                        s.invoke(temp,value.replace(" ",""));
                    }
                }catch (Exception e){
                    e.printStackTrace();
                    continue;
                }
            }
        }

    }


    /**
     * 收发货人信息审核通过
     */
    @Transactional
    public void auditCompanyQpTemps(List<CompanyQpTemp> temps, boolean pass) throws SaveException {
        List<String> ids = temps.stream().map(CompanyQpTemp::getId).collect(Collectors.toList());
        List<String> cos = temps.stream().map(CompanyQpTemp::getCompanyCode).collect(Collectors.toList());

        //step1 检查是否已经存在对应编号的信息
        List<ConsigneeConsignorDP> originalCCDPList = consigneeConsignorDPDao.findAll(cos);
        if (originalCCDPList.size() > 0) {
            String errMsg = originalCCDPList.stream().map(ConsigneeConsignorDP::getCompanyCo).collect(Collectors.toList()).toString();
            throw new SaveException("查到已存有下列编号的数据信息： " + errMsg);
        }

        //step2 保存审核记录
        List<CompanyQpTemp> originalList = baseRepository.findAll(ids);
        for (CompanyQpTemp qpTemp : originalList) {
            temps.stream().filter(temp -> qpTemp.getId().equals(temp.getId())).forEach(temp -> {
                qpTemp.setCompanyName(temp.getCompanyName());
                qpTemp.setCompanyCode(temp.getCompanyCode());
                qpTemp.setCompanyCoUnite(temp.getCompanyCoUnite());
                qpTemp.setCompanyAddress(temp.getCompanyAddress());
                qpTemp.setCompanyPhone(temp.getCompanyPhone());
                qpTemp.setCompanyFax(temp.getCompanyFax());
                qpTemp.setAuditRemark(temp.getAuditRemark());
                qpTemp.setClosed(CompanyQpTemp.CLOSED_1);
                qpTemp.setAuditor(LoginUtil.getLoginUser());
                qpTemp.setAuditTime(new Date());
                qpTemp.setAuditResult(pass ? CompanyQpTemp.RESULT_PASS : CompanyQpTemp.RESULT_REFUSE);
            });
        }
        baseRepository.save(originalList);
        LOGGER.info("临时收发货人信息审核: " + originalList + "{审核人：" + LoginUtil.getLoginUser().getName() + "}");

        //step3 通过审核则保存正式收发货人数据
        if (pass) {
            List<CompanyQp> qps = new ArrayList<>();
            for (CompanyQpTemp qpTemp : originalList) {
                CompanyQp qp = new CompanyQp();
                qp.setCompanyCode(qpTemp.getCompanyCode());
                qp.setCOMPANY_NAME(qpTemp.getCompanyName());
                qp.setCompanyCoUnite(qpTemp.getCompanyCoUnite());
//                qp.setReferenceCompanyId(qpTemp.getReferenceCompanyId());
                qps.add(qp);
            }
            companyQpDao.save(qps);
            LOGGER.info("保存为正式收发货人信息: " + qps);
        }

    }

    /**
     * 根据编号和公司全称查询申报公司信息是否通过审核
     *
     * @param code 编号
     * @param name 全称
     * @return reset-重新选择下拉框，success-可用，fail-不可用，error-查询错误
     */
    public String queryCompanyState(String code, String name) {
        String sql = "select t.company_code from cdams_qp_companys t where t.company_code = :code and t.company_name = :name";
        Map<String, Object> parameters = new HashMap<>();
        parameters.put("code", code);
        parameters.put("name", name);
        try {
            List<Object> rs = baseRepository.findEntityBySql(sql, 0, 0, parameters);
            if (rs.size() == 0) {
                List<Object> temp_rs = baseRepository.findEntityBySql("select t.audit_result_ from cdams_qp_companys_temp t where t.company_code = :code and t.company_name = :name", 0, 0, parameters);
                if (temp_rs.size() == 0) {
                    return "reset";
                } else {
                    Object o = temp_rs.get(0);
                    return (o != null && CompanyQpTemp.RESULT_PASS.equals(o)) ? "success" : "fail";
                }
            }else{
                return "success";
            }
        } catch (QueryException e) {
            e.printStackTrace();
            return "error";
        }
    }

    /**
     * 按照jqgrid参数进行查询
     */
    public Page<CompanyQpTemp> queryCompanyQpTempByJqgrid(Jqgrid jqgrid) {
        try {
            return baseRepository.findByJqgrid(jqgrid);
        } catch (QueryException e) {
            LOGGER.info("查询待审核收发货人数据时出现异常【jqgrid:" + jqgrid.toString() + "】");
            return null;
        }
    }

    /**
     * 通过id的集合查询临时收发货人信息
     *
     * @param idList id集合
     * @return 收发货人信息
     */
    public List<CompanyQpTemp> queryCompanyQpTempByIdList(List<String> idList) {
        return companyQpTempDao.findByIdIn(idList);
    }

    /**
     * 查找审核收发货人是否有重复
     * @param companyName
     * @return true-已存在公司名，false-没有存在公司名
     */
    public boolean checkExistByCompanyName(String companyName){
        String sql = "select * from CDAMS_QP_COMPANYS_TEMP t where t.company_name=:company_name and t.closed_='0'";
        Map<String,Object> parameters = new HashMap<>();
        parameters.put("company_name",companyName);
        try {
            int count = companyQpTempDao.findEntityCountBySql(sql,parameters);
            if(count>0){
                return true;
            }
        } catch (QueryException e) {
            e.printStackTrace();
        }
        return false;
    }
}
